import React, { useState, useRef,useEffect } from 'react';
import { Modal, Button, Tag, message } from 'antd';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { history } from 'umi';
import { TableListItem } from '../../Plan/data.d';
import { materialDetail } from '../service';
import styles from '../index.less';

interface PlanComponentProps {
    modalVisible: boolean;
    onCancel: () => void;
    id: number;
}

//容量单位转换(kb,mb,gb,tb)
const bytesToSize = (bytes:any) =>{
  if (bytes === 0) return '0 B';
  let k = 1024,
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));

  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}

const ProgramModel: React.FC<PlanComponentProps> = (props) => {
  const actionRef = useRef<ActionType>();
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState<boolean>(false);
  const { modalVisible, onCancel, id} = props;

  useEffect(() => {
    if(modalVisible){
      setLoading(true);
        new Promise((resolve, reject) => {
          materialDetail(id)
              .then((res) => {
                if(res){
                  if (res.code === 200) {
                    let data = res.data;
                    const list = data.programs;
                    for(let i in list){
                      list[i].index = parseInt(i)+1;//序号
                      list[i].key = list[i].id;
                      list[i].index = parseInt(i)+1;
                      list[i].resolution = list[i].resolutionWidth + ' x ' + list[i].resolutionHeight;
                      list[i].totalSize = bytesToSize(parseInt(list[i].totalSize));
                    }
                    setDataSource(list)
                    resolve(true);
                  } else {
                    message.error('请求失败，' + res.message);
                    resolve(false);
                  }
                }
                setLoading(false);
              })
              .catch((error) => {
                message.error('请求失败');
                reject(error);
              });
          });
    }},[modalVisible]);

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'text',
      width:50,
    },
    {
      title: '节目名称',
      dataIndex: 'name',
      ellipsis:true,
      width:150,
      valueType: 'text',
    },
    {
      title: '分辨率',
      dataIndex: 'resolution',
      valueType: 'text',
    },
    {
      title: '节目时长',
      dataIndex: 'totalTime',
      valueType: 'text',
      width:80,
      hideInSearch: true,
      render: (_, record) => <>{record.totalTime}秒</>,
    },
    {
      title: '节目大小',
      dataIndex: 'totalSize',
      valueType: 'text',
      width:80,
      hideInSearch: true,
    },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'text',
      width:150,
      hideInSearch: true, 
      render: tags => (
        <>
          {tags?.map((tag, index) => {
            return (
              <Tag color="blue" key={index} title={tag.name} style={{marginBottom:5,display:'inline-block',overflow:'hidden',whiteSpace:'pre',textOverflow:'ellipsis',maxWidth:130}}>
                {tag.name}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '作者',
      dataIndex: 'author',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width:50,
      render: (_, record) => (
        <>
          <a
            disabled={localStorage.getItem("authority").indexOf("program:list")>-1?false:true}
            onClick={() => {
              history.push({pathname:'/program/list/'});
            }}
          >
            查看
          </a>
        </>
      ),
    },
  ];

  return (
    <Modal
        destroyOnClose
        title="引用节目"
        className={styles.ProgramModel}
        width={960}
        centered
        visible={modalVisible}
        onCancel={() => onCancel()}
        footer={[
        <>
        <Button key="cancel" onClick={onCancel}>返回</Button>
        </>
        ]}
    >
        <ProTable<TableListItem>
            size="small"
            options={false}
            actionRef={actionRef}
            rowKey="key"
            search={false}
            loading={loading}
            pagination={{ showQuickJumper: true,defaultPageSize: 10 }}
            columns={columns}
            dataSource={dataSource}
            scroll={{y:240}}
        />
    </Modal>
  );
};

export default ProgramModel;
